package service;

import dao.StoresManagement;
import model.PicturesInfo;
import model.Store;
import org.apache.commons.fileupload.FileItem;
import util.Common;

import java.io.File;
import java.util.List;

public class StoreServiceImp implements StoreService {

    private final StoresManagement storeMan;
    private final AccountService   accountService;

    public StoreServiceImp(StoresManagement storeMan, AccountService accountService) {
        this.storeMan        = storeMan;
        this.accountService  = accountService;
    }

    @Override
    public Long openNewStore(long creatorID, String userPass, String storeName, FileItem pic, String storePicHome) throws Exception {

        //验证用户身份
        if(accountService.verificate(creatorID, userPass) != AccountService.LoginState.SUCCEED) return null;

        //获取文件名，拼接文件存储路径
        String fileName = pic.getName();

        //设置商店图片封面信息
        PicturesInfo picCfg = new PicturesInfo();
        picCfg.setIndex(fileName);

        String picStorePath = storePicHome + '/' + storeName;

        //调用DAO，增加店铺
        Long st_id = storeMan.openStore(creatorID, storeName, picCfg.toString());

        //如果记录成功插入，则将图片存入磁盘
        if(st_id != null) {
            Common.initDirectory(picStorePath);
            pic.write(new File(picStorePath + '/' + fileName));
        }

        return st_id;
    }

    @Override
    public List<Store> getStories(long creatorID, String userPass) {
        //验证用户身份
        if(accountService.verificate(creatorID, userPass) != AccountService.LoginState.SUCCEED) return null;
        return storeMan.findByCreator(creatorID);
    }
}
